import mitt from '@/mitt'
let timeout = null
/**
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
export function debounce(func, wait = 500, immediate = false) {
  // 清除定时器
  if (timeout !== null) clearTimeout(timeout)
  // 立即执行，此类情况一般用不到
  if (immediate) {
    var callNow = !timeout
    timeout = setTimeout(function () {
      timeout = null
    }, wait)
    if (callNow) typeof func === 'function' && func()
  } else {
    // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
    timeout = setTimeout(function () {
      typeof func === 'function' && func()
    }, wait)
  }
}

// eslint-disable-next-line no-unused-vars
let timer, flag
/**
 * 节流原理：在一定时间内，只能触发一次
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
export function throttle(func, wait = 500, immediate = true) {
  if (immediate) {
    if (!flag) {
      flag = true
      // 如果是立即执行，则在wait毫秒内开始时执行
      typeof func === 'function' && func()
      timer = setTimeout(() => {
        flag = false
      }, wait)
    }
  } else {
    if (!flag) {
      flag = true
      // 如果是非立即执行，则在wait毫秒内的结束处执行
      timer = setTimeout(() => {
        flag = false
        typeof func === 'function' && func()
      }, wait)
    }
  }
}

/**
 * @description: 获取屏幕工作区域的高度和宽度（去掉状态栏）
 * @return {*}
 */
export function getScreenHeight() {
  return document.documentElement.clientHeight
}

/**
 * @description: 生成消息ID
 * @return {*}
 */
export function generateRandId() {
  var d = new Date().getTime()
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
  })
  return uuid
}

/**
 * @description: 处理时间
 * @param {*} timestamp
 * @param {*} type
 * @param {*} text
 * @return {*}
 */
export function parseDate(timestamp, type, text) {
  /**
   * @timetamp  时间戳
   * @type 类型
   * @text 拼接的字符串
   */
  let date = new Date(timestamp)
  let Y = ''
  let M = ''
  let D = ''
  if (type == 'Chinese') {
    Y = date.getFullYear() + '年'
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月'
    D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日'
    return M + D
  }
  Y = date.getFullYear() + text
  M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + text
  const h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
  const m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':'
  const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds() // 秒
  if (type == 'full') {
    D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
    return Y + M + D + h + m + s
  }
  if (type == 'simple') {
    D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    return Y + M + D
  }

  if (type == 'time') {
    return h + m + s
  }
}

/**
 * @description: 消息时间格式化
 * @param {*} dateTimeStamp 时间戳
 * @param {*} $t i18n对象
 * @return {*}
 */
export function caculateTimeago(dateTimeStamp, $t) {
  const minute = 1000 * 60 // 把分，时，天，周，半个月，一个月用毫秒表示

  const hour = minute * 60
  const day = hour * 24
  const week = day * 7
  const now = new Date().getTime() // 获取当前时间毫秒

  const diffValue = now - dateTimeStamp // 时间差

  let result = ''

  if (diffValue < 0) {
    return
  }

  const minC = diffValue / minute // 计算时间差的分，时，天，周，月

  const hourC = diffValue / hour
  const dayC = diffValue / day
  const weekC = diffValue / week

  if (weekC >= 1 && weekC <= 4) {
    // result = ` ${parseInt(weekC, 10)}周前`;
    result = ` ${parseInt(weekC, 10)}${$t('chat.weeksAgo')}`
  } else if (dayC >= 1 && dayC <= 6) {
    // result = ` ${parseInt(dayC, 10)}天前`;
    result = ` ${parseInt(dayC, 10)}${$t('chat.daysAgo')}`
  } else if (hourC >= 1 && hourC <= 23) {
    // result = ` ${parseInt(hourC, 10)}小时前`;
    result = ` ${parseInt(hourC, 10)}${$t('chat.hoursAgo')}`
  } else if (minC >= 1 && minC <= 59) {
    // result = ` ${parseInt(minC, 10)}分钟前`;
    result = ` ${parseInt(minC, 10)}${$t('chat.minutesAgo')}`
  } else if (diffValue >= 0 && diffValue <= minute) {
    // result = '刚刚';
    result = $t('chat.justNow')
  } else {
    const datetime = new Date()
    datetime.setTime(dateTimeStamp)
    const Nyear = datetime.getFullYear()
    const Nmonth =
      datetime.getMonth() + 1 < 10 ? `0${datetime.getMonth() + 1}` : datetime.getMonth() + 1
    const Ndate = datetime.getDate() < 10 ? `0${datetime.getDate()}` : datetime.getDate()
    result = `${Nyear}-${Nmonth}-${Ndate}`
  }

  return result
}
/**
 * @description: 检测设备环境
 * @return {*}
 */
export function judgeEquipment() {
  let ua = navigator.userAgent,
    isWindowsPhone = /(?:Windows Phone)/.test(ua),
    isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
    isAndroid = /(?:Android)/.test(ua),
    isFireFox = /(?:Firefox)/.test(ua),
    isChrome = /(?:Chrome|CriOS)/.test(ua),
    isTablet =
      /(?:iPad|PlayBook)/.test(ua) ||
      (isAndroid && !/(?:Mobile)/.test(ua)) ||
      (isFireFox && /(?:Tablet)/.test(ua)),
    isPhone = /(?:iPhone)/.test(ua) && !isTablet,
    isPc = !isPhone && !isAndroid && !isSymbian
  return {
    isTablet,
    isPhone,
    isAndroid,
    isPc,
    isChrome
  }
}

/**
 * @description: flex布局计算补充子元素个数
 * @param {*} boxClassName
 * @param {*} childrenClassName
 * @param {*} number
 * @return {*}
 */
export function LayoutCalculation(boxClassName, childrenClassName, number) {
  let box = document.getElementsByClassName(boxClassName)[0]
  let children = document.getElementsByClassName(childrenClassName)[0]
  if (!children) {
    return
  }
  let clientWidth = box.getBoundingClientRect().right - box.getBoundingClientRect().left
  let childWidth = children.getBoundingClientRect().right - children.getBoundingClientRect().left
  let column = Math.floor(clientWidth / childWidth)
  console.log(column, clientWidth, childWidth)
  return Math.ceil(number / column) * column - number
}

/**
 * @description: 复制功能
 * @param {*} text
 * @return {*}
 */
export function textCopy(text) {
  // 如果当前浏览器版本不兼容navigator.clipboard
  if (!navigator.clipboard) {
    var ele = document.createElement('input')
    ele.value = text
    document.body.appendChild(ele)
    ele.select()
    document.execCommand('copy')
    document.body.removeChild(ele)
    if (document.execCommand('copy')) {
      mitt.emit('messageTip', {
        type: 'success',
        msg: '复制成功'
      })
    } else {
      mitt.emit('messageTip', {
        type: 'error',
        msg: '复制失败！'
      })
    }
  } else {
    navigator.clipboard
      .writeText(text)
      .then(function () {
        mitt.emit('messageTip', {
          type: 'success',
          msg: '复制成功'
        })
      })
      .catch(function () {
        mitt.emit('messageTip', {
          type: 'error',
          msg: '复制失败！'
        })
      })
  }
}

/**
 * @description: 保存 blob 到本地
 * @param {*} fileName 文件名称
 * @param {*} blob blob文件
 * @return {*}
 */
export function saveBlobFile(fileName, blob) {
  return new Promise((resolve, reject) => {
    const fr = new FileReader()
    fr.readAsDataURL(blob)
    fr.onload = function (e) {
      let a = document.createElement('a')
      a.download = fileName
      a.href = e.target.result
      a.click()
      resolve()
    }
    fr.onerror = function (e) {
      reject(e)
    }
  })
}

/**
 * 验证给定的字符串是否为有效的 IPv4 地址
 *
 * @param ip 待验证的字符串
 * @returns 如果字符串是有效的 IPv4 地址，则返回 true；否则返回 false
 */
export function validateIpAddress(ip) {
  const ipRegex =
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
  return ipRegex.test(ip)
}
